package com.ddpt.platform.common.export;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.ddpt.platform.common.export.vo.QueryDataVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;

import java.io.ByteArrayOutputStream;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Set;

/**
 * 导出公共方法处理类
 *
 * @author : zhanggsc
 * @Data : 2023/3/1 11:53
 */
@Slf4j
public class ExportUtil {

    public final static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 上传至minio前准备
     *
     * @param name   文件命名
     * @param vos    数据体
     * @param fields 自定义返回体
     * @return
     */
    public static byte[] export(String name, List<? extends QueryDataVo> vos, Set<String> fields) {
        if (CollectionUtils.isEmpty(vos)) {
            return null;
        }
        List<List<Object>> dataList = vos.get(0).asVos(vos, fields);
        try {
            //生成表格数据
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ExcelWriter excelWriter = EasyExcel.write(os).build();
            WriteSheet writeSheet = EasyExcel.writerSheet(name).build();
            excelWriter.write(dataList, writeSheet);
            //千万别忘记finish 会帮忙关闭流
            excelWriter.finish();
            byte[] bytes = os.toByteArray();
            os.close();
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
